﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HZ.Supervise.Model;
using HZ.Supervise.IBLL;
using System.Data;
using HZ.Supervise.Model.Enum;

public partial class Hospital_HospitaltotalStatistics : BasePage
{

    public Hospital_HospitaltotalStatistics()
    {
        this.ModuleNo = Module.医院统计分析.ToString();
        this.PageOperateType = OperateType.医院汇总统计.ToString();
    }

    private DataTable dtCom;
    protected void Page_Load(object sender, EventArgs e)
    {
        //todo:绑定委托 查询事件
        QueryControl1.OnQueryClick += new EventHandler(QueryControl1_OnQueryClick);

        this.btnExcel.Visible = false;
        if (!IsPostBack)
        {
            ViewState["query"] = URLUtil.GetSuperviseQueryFromURL(Request);

            //todo:第一次加载执行顺序 
            QueryControl1.BindDataPre((SuperviseQuery)ViewState["query"]);//绑定查询条件的一些数据源 质量层次等
            //BindData();//绑定数据
            QueryControl1.BindSort(gvwInfo);

            ChartControl1.Visible = false;

            
            //GetHospitalAccount();
        }
    }

    protected void QueryControl1_OnQueryClick(object sender, EventArgs e)
    {
        AspNetPager1.CurrentPageIndex = 1;

        //todo:点击查询按钮的时候需要 获取查询条件，分页的时候不需要
        
		//BindData()

        this.btnExcel.Visible = true;
       
    }

    protected void BindData()
    {
        int t = 0;

        HZ.Supervise.IBLL.IExecuteContext ie = HZ.Supervise.BLLFactory.ExecuteContext();
        ie.QueryObject = new HZ.Supervise.Model.QueryObject()
        {
            GroupField = GroupByField.HospitalID,
            Query = (SuperviseQuery)ViewState["query"],
            GroupSelectField = GroupFields.PurchaseAmountTotal | GroupFields.WareHouseRate | GroupFields.WareHouseAmountTotal | GroupFields.DistributeAmountTotal | GroupFields.DistributeRate | GroupFields.DecreasingAmplitudeBatch,
            SortField = QueryControl1.SortField == "" ? "HospitalID ASC" : QueryControl1.SortField
        };//todo:绑定排序字段

        dtCom = ie.ExecutePage(AspNetPager1.CurrentPageIndex, AspNetPager1.PageSize, out t);

        //todo:判断如果没数据 那么btnExcel按钮 visible = false  JOHN
        if (dtCom.Rows.Count <= 0)
        {
            this.btnExcel.Visible = false;
        }
        AspNetPager1.RecordCount = t;
        gvwInfo.PageSize = AspNetPager1.PageSize;
        gvwInfo.AutoGenerateColumns = false;
        GridViewUtil.AdjustGridView(gvwInfo, dtCom);
        gvwInfo.DataSource = dtCom;
        gvwInfo.DataBind();
        setChart(dtCom);
        SetColumnVisible();
    }

    protected void AspNetPager1_OnPageChanged(object sender, EventArgs e)
	{
		ViewState["query"] = QueryControl1.UpdateQueryFromValue((SuperviseQuery)ViewState["query"]);
        BindData();
		GetHospitalAccount();
    }


    protected void gvwInfo_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        //按企业查看
        if (e.CommandName == "DirectByCom")
        {
            ////设置分组查询字段GroupSelectField
            if (ShowColumns.ShowColumn == null)
            {
                ShowColumns.ShowColumn = new ShowColumns();
                ShowColumns.ShowColumn.GroupFields = GroupFields.PurchaseAmountTotal | GroupFields.CountOrder;

            }

            string sessionid = Guid.NewGuid().ToString();
            SuperviseQuery query = (SuperviseQuery)ViewState["query"];

            //query.HospitalID = e.CommandArgument.ToString();
            string[] Hospital = e.CommandArgument.ToString().Split(',');
            query.HospitalID = Hospital[0].ToString();
            query.HospitalName = Hospital[1].ToString();
            query._Titile = "医院相关配送企业";
            query._QueryPrompt = query._QueryPrompt + " " + Hospital[1].ToString();
            Session[sessionid] = query;

            string url = System.Configuration.ConfigurationManager.AppSettings["CompanyID_PS"];
            Response.Redirect(string.Format("{0}?sessionid={1}", url, sessionid));
        }

        //按药品查看
        if (e.CommandName == "DierectByDrug")
        {
            //设置分组查询字段GroupSelectField
            //if (ShowColumns.ShowColumn == null)
            //{
            //    ShowColumns.ShowColumn = new ShowColumns();
            //    ShowColumns.ShowColumn.GroupFields = GroupFields.DistributeCountTotal | GroupFields.DistributeRate | GroupFields.PurchaseCountTotal | GroupFields.WareHouseCountTotal;
            //}


            string sessionid = Guid.NewGuid().ToString();
            SuperviseQuery query = (SuperviseQuery)ViewState["query"];

            //query.HospitalID = e.CommandArgument.ToString();
            string[] Hospital = e.CommandArgument.ToString().Split(',');
            query.HospitalID = Hospital[0].ToString();
            query.HospitalName = Hospital[1].ToString();
            query._Titile = "医院相关药品";
            query._QueryPrompt = query._QueryPrompt + " " + Hospital[1].ToString();

            Session[sessionid] = query;
            string url = System.Configuration.ConfigurationManager.AppSettings["ProcureCatalogID"];
            Response.Redirect(string.Format("{0}?sessionid={1}", url, sessionid));
        }

        if (e.CommandName == "DierectByDetail")
        {
            if (ShowColumns.ShowColumn == null)
            {
                ShowColumns.ShowColumn = new ShowColumns();
                ShowColumns.ShowColumn.GroupFields = GroupFields.DistributeCountTotal | GroupFields.DistributeRate | GroupFields.PriceAvg | GroupFields.PurchaseAmountTotal | GroupFields.PurchaseCountTotal | GroupFields.WareHouseAmountTotal | GroupFields.WareHouseCountTotal | GroupFields.WareHouseRate;
            }


            string sessionid = Guid.NewGuid().ToString();
            SuperviseQuery query = (SuperviseQuery)ViewState["query"];

            //query.HospitalID = e.CommandArgument.ToString();
            string[] Hospital = e.CommandArgument.ToString().Split(',');
            query.HospitalID = Hospital[0].ToString();
            query.HospitalName = Hospital[1].ToString();
            query._QueryPrompt = query._QueryPrompt + " " + Hospital[1].ToString();

            Session[sessionid] = query;

            string url = System.Configuration.ConfigurationManager.AppSettings["HosComDrugs"];
            Response.Redirect(string.Format("{0}?sessionid={1}", url, sessionid));
        }

    }



    #region   数据准备

    ///// <summary>
    ///// 根据查询条件 控制连接的显示情况
    ///// </summary>
    private void SetColumnVisible()
    {
        if (!string.IsNullOrEmpty(QueryControl1.ProcureCatalogID))
        {
            foreach (GridViewRow row in gvwInfo.Rows)
            {
                row.FindControl("lbnDrug").Visible = false;
            }
        }
        if (!string.IsNullOrEmpty(QueryControl1.CompanyID_PS))
        {
            foreach (GridViewRow row in gvwInfo.Rows)
            {
                row.FindControl("lbnCom_PS").Visible = false;
            }
        }

    }

    #endregion

    protected void ddlOther_SelectedIndexChanged(object sender, EventArgs e)
    {
        string stkey = "";
        string sessionid = string.Empty;
        GridViewRow row = (GridViewRow)((Control)sender).Parent.Parent;
        DropDownList ddl = (DropDownList)row.FindControl("ddlOther");
        stkey = ddl.SelectedValue;
        if (stkey != "")
        {
            sessionid = Guid.NewGuid().ToString();
            SuperviseQuery query = (SuperviseQuery)ViewState["query"];
            //赋予当前行的主键值
            //query.HospitalID = row.Cells[1].Text; //((LinkButton)row.FindControl("lbnHos")).CommandArgument;
            //query.HospitalName = row.Cells[2].Text;
            query.HospitalID = gvwInfo.DataKeys[row.RowIndex].Values["HospitalID"].ToString();
            query.HospitalName = gvwInfo.DataKeys[row.RowIndex].Values["HospitalName"].ToString();
            query._QueryPrompt = query._QueryPrompt + " " + gvwInfo.DataKeys[row.RowIndex].Values["HospitalName"].ToString();

            Session[sessionid] = query;
            string url = System.Configuration.ConfigurationManager.AppSettings[stkey];
            Response.Redirect(string.Format("{0}?sessionid={1}", url, sessionid));
        }

    }

    /// <summary>
    /// 设置图表
    /// </summary>
    /// <param name="?"></param>
    private void setChart(System.Data.DataTable dt)
    {
        if (dt.Rows.Count > 0)
        {
            this.ChartControl1.Visible = false;
            HZ.Supervise.Web.WebService.ChartConfig serChart = new HZ.Supervise.Web.WebService.ChartConfig();
            dt.TableName = "医院";
            serChart.DataSource = dt;

            if (ShowColumns.ShowColumn == null)
            {
                serChart.XName = "HospitalName";
                serChart.YNames = "PurchaseAmountTotal";
            }
            else
            {
                string[] _columns = ShowColumns.ShowColumn.GroupFields.ToString().Split(',');
                serChart.XName = "HospitalName";
                serChart.YNames = _columns[0];
            }

            serChart.ChartTypes = HZ.Supervise.Web.WebService.ChartType.ColumnChart;

            ChartControl1.webChart = serChart;
            ChartControl1.PageId = Guid.NewGuid().ToString();
            ChartControl1.EntranceChart();
        }
        else
        {
            ChartControl1.Visible = false;
        }
    }
    protected void lbtnSee_Click(object sender, EventArgs e)
    {
        if (this.lbtnSee.Text == "显示图表")
        {
            ChartControl1.Visible = true;

            this.lbtnSee.Text = "隐藏图表";
        }
        else
        {
            ChartControl1.Visible = false;
            this.lbtnSee.Text = "显示图表";
        }
    }


    protected void btnExcel_Click(object sender, EventArgs e)
    {
        int t = 0;

        HZ.Supervise.IBLL.IExecuteContext ie = HZ.Supervise.BLLFactory.ExecuteContext();
        ie.QueryObject = new HZ.Supervise.Model.QueryObject()
        {
            GroupField = GroupByField.HospitalID,
            Query = (SuperviseQuery)ViewState["query"],
            GroupSelectField = GroupFields.PurchaseAmountTotal | GroupFields.WareHouseRate | GroupFields.WareHouseAmountTotal | GroupFields.DistributeAmountTotal | GroupFields.DistributeRate | GroupFields.DecreasingAmplitudeBatch,
            SortField = QueryControl1.SortField == "" ? "HospitalID ASC" : QueryControl1.SortField
        };//todo:绑定排序字段

        DataTable dt = ie.ExecutePage(0, 0, out t);
        //GridViewUtil.AdjustGridView(gvwInfo, dt);  
        ExportFile.Instance.ExportData(dt, gvwInfo, this.Page);
    }
    /// <summary>
    /// 涉及医院的个数
    /// </summary>
    public void GetHospitalAccount()
    {
        int t = 0;

        HZ.Supervise.IBLL.IExecuteContext ie = HZ.Supervise.BLLFactory.ExecuteContext();
        ie.QueryObject = new HZ.Supervise.Model.QueryObject()
        {
            GroupField = GroupByField.HospitalID,
            Query = (SuperviseQuery)ViewState["query"],
            GroupSelectField = GroupFields.PurchaseAmountTotal | GroupFields.WareHouseRate | GroupFields.WareHouseAmountTotal | GroupFields.DistributeAmountTotal | GroupFields.DistributeRate | GroupFields.DecreasingAmplitudeBatch,
            SortField = QueryControl1.SortField == "" ? "HospitalID ASC" : QueryControl1.SortField
        };//todo:绑定排序字段

        dtCom = ie.ExecutePage(1, 0, out t);
        int i = dtCom.Rows.Count;
        double PurchaseAmountTotal = 0;//采购总金额
        double DistributeAmountTotal = 0;//配送总金额
        double WareHouseAmountTotal = 0; //入库总金额
      
        if (i > 0)
        {
            for (int j = 0; j < i; j++)
            {

                PurchaseAmountTotal += HZ.MathUtil.SToF(dtCom.Rows[j]["PurchaseAmountTotal"].ToString());
                DistributeAmountTotal += HZ.MathUtil.SToF(dtCom.Rows[j]["DistributeAmountTotal"].ToString());
                WareHouseAmountTotal += HZ.MathUtil.SToF(dtCom.Rows[j]["WareHouseAmountTotal"].ToString());
            }

            lblCount.Text = "采购总金额为:" + PurchaseAmountTotal.ToString("N2") + ";配送总金额为:" + DistributeAmountTotal.ToString("N2") + ";入库总金额为:" + WareHouseAmountTotal.ToString("N2") + "";
        }
        else
        {
            lblCount.Text = "暂无符合条件的数据！";
        }
    }
}
